package com.sslite.standalone;

import java.io.File;
import java.util.Date;
import java.util.List;

import com.sslite.model.MetaData;
import com.sslite.util.SSLiteProperties;
import com.sslite.util.Utility;

public class IntraDayDownloader {

	public static void downloadIntraDayDataFromGoogle(final List<MetaData> metaDataList, final List<String> exceptionSymbols, final List<String> exceptionOneMinuteSymbols) throws Exception{
		int ctr = 0;
		
		for(final MetaData metaData : metaDataList){
			System.out.print( "IntraDayDownloader: Downloading " +metaData.getSymbol()+ " " );
			
			if( exceptionSymbols.size() >= 5 ){
				System.out.println( "\nIntraDayDownloader: Exception occured for more than 5 symbols " +exceptionSymbols+ " at " +new Date() );
				System.out.println( "Manually Fix exceptionOneMinuteSymbols: " +exceptionOneMinuteSymbols+ ".\nExiting now." );
				//System.out.println( "\007\007\007" ); // Beep Character \007
				System.exit(-1);
			}
			
			try{
				// ********************************* START: CACHE IMPLEMENTATION ********************************** //
				final String CACHE_FILE_SUFFIX_INTRA_DAY = "-INTRA-DAY";
				String source = "";
				
				String intraDayContent = null;
				try{
					File intraDayFile = new File( SSLiteProperties.CACHE_FOLDER.getValue() + metaData.getSymbol() + CACHE_FILE_SUFFIX_INTRA_DAY );
					if( intraDayFile.exists() ){
						source = "(offline)";
						System.out.println( source );
						intraDayContent = Utility.getContent( intraDayFile.toURL().toString() );
					}
				}
				catch(Exception e){
					e.printStackTrace();
				}

				if( intraDayContent == null ){
					source = "(online)";
					System.out.println( source );
					intraDayContent = Utility.getContent( SSLiteProperties.GOOGLE_URL_INTRA_DAY.getValue().replaceAll("~SYMBOL", metaData.getSymbol()) );
					try{
						Utility.saveContent(SSLiteProperties.CACHE_FOLDER.getValue() + metaData.getSymbol() + CACHE_FILE_SUFFIX_INTRA_DAY, intraDayContent);

						try{
							appendToIntraDayFile(metaData.getSymbol(), intraDayContent);
						}
						catch(Exception e){
							exceptionOneMinuteSymbols.add( metaData.getSymbol() );
						}
					}
					catch(Exception e){
						e.printStackTrace();
					}
				}
				// ********************************* END: CACHE IMPLEMENTATION ********************************** //
			}
			catch(Exception e){
				System.out.println( "IntraDayDownloader: ****************** Exception occured while processing " +metaData.getSymbol()+ " -> " +e.getMessage() );
				exceptionSymbols.add(metaData.getSymbol());
			}
			
			try{
				if( ++ctr >= 20 ){
					ctr = 0;
					int sleepTimeMillis = Integer.parseInt(SSLiteProperties.SLEEP_TIME_MILLIS.getValue());
					System.out.println( "\nIntraDayDownloader: Sleeping for " +sleepTimeMillis+ " millis .... " );
					Thread.sleep(sleepTimeMillis);
				}
			}
			catch(Exception e){
			}
		}
		
		if( !exceptionSymbols.isEmpty() ){
			System.out.println( "\nIntraDayDownloader: Could not process " +exceptionSymbols.size()+ " symbols: " +exceptionSymbols );
		}
		
		if( !exceptionOneMinuteSymbols.isEmpty() ){
			System.out.println( "\nIntraDayDownloader: Could not save one.minute data for : " +exceptionOneMinuteSymbols+". To resolve delete <SYMBOL>-INTRA-DAY file from cache.folder, remove any zero-volume entries towards the end of one.minute file for these symbols and rerun the process for these symbols with generate.report.only=false. \nCaution: Keep a copy of generated report otherwise it will overwrite it and you will have to re-run report again for all symbols." );
		}
	}
	
	private static void appendToIntraDayFile(final String symbol, final String content){
		try{
			File existingIntraDayFile = new File( SSLiteProperties.ONE_MINUTE_DATA_FOLDER.getValue() +"/"+ symbol+"-INTRA-DAY" );
			if( existingIntraDayFile.exists() ){ // Append
				String existingContent = Utility.getContent( existingIntraDayFile.toURL().toString() );
				// Read Last line
				final String[] arrExistingContent = existingContent.split("[\n]");
				String lastLineWithVolume = null;
				if( arrExistingContent.length >= 25 ){ // To be on safe side, pull last 25 min data
					for( int i=(arrExistingContent.length-25); i<arrExistingContent.length; i++ ){
						final String line = arrExistingContent[i];
						
						String cols[] = line.split(",");
						if( !cols[cols.length-1].equals("0") ){ // Last Column Volume
							lastLineWithVolume = arrExistingContent[i];
							break;
						}
					}
					System.out.println( "\tIntraDayDownloader: lastLineWithVolume: "+lastLineWithVolume );
				}
				
				// Find last line in content
				int indexOfLastLineWithVolume = -1;
				if( lastLineWithVolume != null ){
					indexOfLastLineWithVolume = content.lastIndexOf( lastLineWithVolume );
				}
				
				// Append to file.
				final String contentToAppend = content.substring( indexOfLastLineWithVolume );
				Utility.saveContent( existingIntraDayFile.getAbsolutePath(), existingContent.substring(0, existingContent.indexOf(lastLineWithVolume) ).trim()+"\n"+contentToAppend.trim());
				System.out.println( "IntraDayDownloader: Successfully appended one.minute data for " +symbol );
			}else{ // Save as is.
				Utility.saveContent(existingIntraDayFile.getAbsolutePath(), content);
				System.out.println( "IntraDayDownloader: Successfully created new one.minute data for [" +symbol+ "] as no existing one.minute data was present." );
			}
		}
		catch(Exception e){
			System.out.println( "IntraDayDownloader: ********* Exception in saving one.minute data for " +symbol );
			e.printStackTrace();
		}
		
	}
	
}


